


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>layuiAdmin 网站用户 iframe 框</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="../layui/css/layui.css" media="all">
</head>
<style>
  .layui-form-select{
    width:200px
  }
  .layui-select-title{
    width:200px
  }
  .layui-input{
    width: 200px;
  }
  
</style>
<body>

  <div class="layui-form" lay-filter="layuiadmin-form-useradmin" id="layuiadmin-form-useradmin" style="padding: 20px 0 0 0;">
    <div class="layui-form-item">
      <label class="layui-form-label">用户名</label>
      <div class="layui-input-inline">
        <input type="text" name="username" lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">头像</label>
      <div class="layui-input-inline">
        <input type="text" name="avatar" lay-verify="required"
               placeholder="请上传图片" autocomplete="off" class="layui-input">
        <div id="avatarPreview" style="margin-top: 10px;"></div>
      </div>
      <button type="button" class="layui-btn" id="layuiadmin-upload-useradmin">
        <i class="layui-icon"></i>上传图片
      </button>
    </div>
    <div class="layui-form-item" lay-filter="birthday">
      <label class="layui-form-label">出生日期</label>
       <div class="layui-input-inline">
        <input type="text" name="birthday" id="date" lay-verify="date" lay-verType="tips" class="layui-input" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
       </div>
      </div>
    <div class="layui-form-item" lay-filter="sex">
      <label class="layui-form-label">选择性别</label>
      <div class="layui-input-block" >
        <select name="sex" >
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </div>
    </div>
      <div class="layui-form-item">
        <label class="layui-form-label">学号</label>
              <div class="layui-input-block">
                <input type="text" name="id" placeholder="请输入" autocomplete="off" class="layui-input">
              </div>
        </div>
      <div class="layui-form-item">
        <label class="layui-form-label">院系</label>
              <div class="layui-input-block" style="width: 220px;">
                <select name="department">
                  <option value="0">不限</option>
                  <option value="1">大数据与基础科学学院</option>
                  <option value="2">石油工程学院</option>
                  <option value="3">智能制造与控制工程学院</option>
                  <option value="4">教育与现代媒体学院</option>
                </select>
              </div>
      </div>
    <div class="layui-form-item">
      <label class="layui-form-label">手机号</label>
      <div class="layui-input-inline">
        <input type="text" name="phone" lay-verify="phone" placeholder="请输入号码" autocomplete="off" lay-verify="required" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">邮箱</label>
      <div class="layui-input-inline">
        <input type="text" name="email" lay-verify="email" lay-verify="required" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
      </div>
    </div>
    
    
  </div>
  <script src="./JS/utils/request.js"></script>
  <script src="./JS/utils/auth.js"></script>
  <script src="../layui/layui.all.js"></script>  
  <script>
 layui.laydate.render({
  elem: '#date'
});
layui.use(['form', 'jquery','upload'], function(){
            let form = layui.form;
            let $ = layui.$;
            let upload = layui.upload

            // 获取院系下拉菜单的动态请求列表
            $.ajax({
              url: '/users/getDepartments', // 替换为实际接口地址
              type: 'GET',
              headers:{
              'Authorization':localStorage.getItem('token')
    },
              success: function(res) {
                console.log(res)
                if (res.code === 0) { // 根据实际接口返回状态码调整
                  var selectHtml = '';

                  // 遍历返回数据生成option
                  res.data.forEach(function(item) {
                    selectHtml += '<option value="' + item.departmentId + '">' + item.departmentName + '</option>';
                  });

                  // 更新select内容
                  $('select[name="department"]').html(selectHtml);

                  // 重新渲染表单
                  form.render('select');
                }
              },
              error: function(xhr, status, error) {
                console.error('分类数据获取失败:', error);
              }
            });

            // 定义提交方法供父页面调用
            window.submitForm = function(callback) {
                // 表单验证
                form.verify();
                
                // 获取表单数据
                let formData = {
                    username: $('input[name="username"]').val(),
                    gender:$('select[name="sex"]').val(),
                    birthdate:$('input[name="birthday"]').val(),
                    userId:$('input[name="id"]').val(),
                    departmentId:$('select[name="department"]').val(),
                    phone:$('input[name="phone"]').val(),
                    email: $('input[name="email"]').val(),
                    avatar:$('#avatarPreview img').attr("src")
                };

                console.log(formData);
                if(formData.birthdate===null){
                  layer.msg("出生日期不能为空！")
                }
                // 发送AJAX请求
                $.ajax({
                    url: '/users/insert',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    headers:{
              'Authorization':localStorage.getItem('token')
    },
                    success: function(res){
                      console.log(res)
                        if(res.code === 0){
                            callback(true);
                        } else {
                            layer.msg(res.msg || '提交失败');
                            callback(false);
                        }
                    },
                    error: function(xhr){
                        layer.msg('请求失败: 手机号和邮箱不能为空！');
                        callback(false);
                    }
                });
            };

            // 初始化上传组件
            upload.render({
              elem: '#layuiadmin-upload-useradmin',
              url: '/users/upload', // 上传接口
              accept: 'images',   // 只允许选择图片文件
              acceptMime: 'image/*', // 限制文件类型
              size: 500,          // 500KB限制
              headers:{
              'Authorization':localStorage.getItem('token')
    },
              done: function(res){
                // console.log(res)
                if(res.code === 0) {
                  layer.msg('上传成功');
                  // 预览图片
                  $('#avatarPreview').html(
                          `<img src="${res.data}" style="max-width: 100px; margin-top: 10px;">`
                  );
                } else {
                  layer.msg(res.msg || '上传失败');
                }
              },
              error: function(){
                layer.msg('上传失败，请检查网络连接');
              }
            });

            // 暴露初始化方法供父页面调用用于编辑信息时的数据回显
            window.initFormData = function(data){
              // 填充表单数据
              form.val('layuiadmin-form-useradmin', {
                "username": data.username,
                "sex": data.gender,
                "birthday": data.birthdate,
                "id":data.userId,
                "department":data.departmentId,
                "phone":data.phone,
                "email":data.email,
              });
              // 预览图片
              $('#avatarPreview').html(
                      `<img src="${data.avatar}" style="max-width: 100px; margin-top: 10px;">`
              );
// 更改信息时学号为只读不可更改
              $('input[name="id"]').attr('readonly',true);
              // 重新渲染表单
              form.render();
            };

        //     保存更改后的表单数据
        // 定义提交方法供父页面调用
        window.updateForm = function(callback) {
          // 表单验证
          form.verify();

          // 获取表单数据
          let formData = {
            username: $('input[name="username"]').val(),
            gender:$('select[name="sex"]').val(),
            birthdate:$('input[name="birthday"]').val(),
            userId:$('input[name="id"]').val(),
            departmentId:$('select[name="department"]').val(),
            phone:$('input[name="phone"]').val(),
            email: $('input[name="email"]').val(),
            avatar:$('#avatarPreview img').attr("src")
          };

          console.log(formData);


          // 发送AJAX请求
          $.ajax({
            url: '/users/update',
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            headers:{
              'Authorization':localStorage.getItem('token')
    },
            success: function(res){
              console.log(res)
              if(res.code === 0){
                callback(true);
              } else {
                layer.msg(res.msg || '更新失败');
                callback(false);
              }
            },
            error: function(xhr){
              layer.msg('请求失败: 院系不能为空！' + xhr.statusText);
              callback(false);
            }
          });
        };


        });
  </script>
</body>
</html>